//
//  ShopCartVC.swift
//  mySwift
//
//  Created by X-MEN on 2021/12/7.
//

import UIKit
import AVFoundation
import AudioKit




class ShopCartVC: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    
    var collectionView: UICollectionView!
    var timer: Timer?
    var lines: [CGFloat] = []
    
    var recorder : Recorder = Recorder(stateEventHandler: StateStreamHandler(), recordEventHandler: RecordStreamHandler())
    
    var audioPlayer: AVAudioPlayer?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //        lines = [40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40];
        //        let layout = UICollectionViewFlowLayout()
        //        layout.scrollDirection = .horizontal
        //        layout.minimumInteritemSpacing = 5
        //        layout.minimumLineSpacing = 5
        //
        //        collectionView = UICollectionView(frame: CGRect(x: 0, y: 100, width: 200, height: 50), collectionViewLayout: layout)
        //        collectionView.showsHorizontalScrollIndicator = false
        //        collectionView.backgroundColor = UIColor.lightGray
        //        collectionView.dataSource = self
        //        collectionView.delegate = self
        //        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
        //        view.addSubview(collectionView)
        //        // 将collectionView翻转180度
        //        collectionView.transform = CGAffineTransform(rotationAngle: .pi)
        //        //如果有默认一组数据则需要滚到到最左边
        //        //        collectionView.scrollToItem(at: IndexPath(item: 0, section: 0), at: .left, animated: false)
        //        //
        //        //        // 开始定时器
        //        timer = Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(updateLines), userInfo: nil, repeats: true)
        //
        // 使用你的 Ogg 文件 URL
        
    }
    
    var player: AVPlayer?

    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        //        if let url = URL(string: "https://us1-dev.propertyraptor.com/hornet/src?p=/IMS/hornet/prp/whatsapp/2024-04/661363b10cf2e5c1f03161a2.ogg") {
        //            downloadAndConvertOggToMp3(from: url)
        //        }
        //
    
       
//        requestMicrophoneAccess();
        
        // 替换为您的 MP3 文件 URL
              guard let url = URL(string: "https://static.superlala.cn/voice/202401/589df812c7e5404191207d6d69e9d9d6.mp3") else {
                  print("无效的 URL")
                  return
              }

        let player = AudioPlayer(url: url)
        player?.play()
        
    }
    

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        print("长按结束");
        self.recorder.stop { path in
            print("录音路径: \(path)")
            self.getDataSize(filePath: path ?? "")
            // 录音文件的路径
            let recordingPath = path
            let recordingUrl = URL(fileURLWithPath: recordingPath ?? "")
            self.playMp3File(url: recordingUrl)
            
        }
    }
    
    func getDataSize(filePath: String) -> Int? {
        do {
            // 从文件路径创建 URL
            let fileURL = URL(fileURLWithPath: filePath)
            // 从 URL 读取文件内容到 Data
            let fileData = try Data(contentsOf: fileURL)
            // 获取 Data 的大小
            let dataSize = fileData.count
            return dataSize
        } catch {
            print("无法读取文件: \(error)")
            return nil
        }
    }
    
    
    func requestMicrophoneAccess() {
        AVAudioSession.sharedInstance().requestRecordPermission { granted in
            if granted {
                print("麦克风访问已授权")
                //否则就转换
                if let documentsDirectory = self.getDownloadFolder() {
                    let mp3Url = documentsDirectory.appendingPathExtension("m4a")
                    do {
                        try self.recorder.start(config: RecordConfig(encoder: AudioEncoder.pcm16bits.rawValue, bitRate: 128000, sampleRate: 44100, numChannels: 2), path: mp3Url.path)
                        
                    } catch {
                        print("录音出错: \(error)")
                    }
                    
                    
                }
                
            } else {
                print("麦克风访问被拒绝")
            }
        }
    }
    
    
    func playMp3File(url: URL) {
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: url)
            audioPlayer?.prepareToPlay()
            audioPlayer?.play()
        } catch {
            print("播放 MP3 文件时出错: \(error)")
        }
    }
    
    func downloadAndConvertOggToMp3(from url: URL) {
        downloadOggFile(from: url) { oggUrl in
            guard let oggUrl = oggUrl else {
                print("下载 Ogg 文件失败")
                return
            }
            //判断已经是下载的mp3文件了就直接播放
            if oggUrl.path.contains("mp3") {
                print(oggUrl);
                self.playMp3File(url: oggUrl)
                return
            }
            //否则就转换
            if let documentsDirectory = self.getDownloadFolder() {
                let mp3Url = documentsDirectory.appendingPathComponent(oggUrl.deletingPathExtension().lastPathComponent).appendingPathExtension("mp3")
                let success = self.convertOggToMp3(inputUrl: oggUrl, outputUrl: mp3Url)
                if success {
                    do {
                        try FileManager.default.removeItem(atPath: oggUrl.path)
                    } catch {
                        print("将原文件删除时出错: \(error)")
                    }
                    print(mp3Url);
                    self.playMp3File(url: mp3Url)
                } else {
                    print("将 Ogg 转换为 MP3 失败")
                }
            }
            
        }
    }
    
    func downloadOggFile(from url: URL, completion: @escaping (URL?) -> Void) {
        if let  folderUrl = getDownloadFolder() {
            // 检查是否已存在相同的 MP3 文件
            let destinationUrl = folderUrl.appendingPathComponent(url.lastPathComponent).deletingPathExtension().appendingPathExtension("mp3")
            if FileManager.default.fileExists(atPath: destinationUrl.path) {
                print("已存在相同的 MP3 文件：\(destinationUrl)")
                completion(destinationUrl)
                return
            }
            
            // 检查是否已存在已相同名称的文件
            let oggUrl = folderUrl.appendingPathComponent(url.lastPathComponent).deletingPathExtension()
            if FileManager.default.fileExists(atPath: oggUrl.path) {
                print("已存在下载文件：\(oggUrl)")
                completion(oggUrl)
                return
            }
            
            let task = URLSession.shared.downloadTask(with: url) { (tempLocalUrl, response, error) in
                if let tempLocalUrl = tempLocalUrl, error == nil {
                    // 成功：将文件移动到永久位置
                    if let documentsDirectory = self.getDownloadFolder() {
                        let destinationUrl = documentsDirectory.appendingPathComponent(url.lastPathComponent)
                        do {
                            try FileManager.default.moveItem(at: tempLocalUrl, to: destinationUrl)
                            completion(destinationUrl)
                        } catch {
                            print("将文件移动到文档目录时出错: \(error)")
                            completion(nil)
                        }
                    }
                    
                } else {
                    print("下载错误: \(error?.localizedDescription ?? "未知错误")")
                    completion(nil)
                }
            }
            task.resume()
            
        } else {
            print("获取下载目录失败")
        }
        
    }
    
    private func getDownloadFolder() -> URL? {
        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let uniqueFolderName = "DownloadedFiles"
        
        let uniqueFolderUrl = documentsDirectory.appendingPathComponent(uniqueFolderName)
        if !FileManager.default.fileExists(atPath: uniqueFolderUrl.path) {
            do {
                try FileManager.default.createDirectory(at: uniqueFolderUrl, withIntermediateDirectories: true, attributes: nil)
                print("独立文件夹创建成功：\(uniqueFolderUrl)")
            } catch {
                print("无法创建独立文件夹：\(error)")
                return nil
            }
        }
        return uniqueFolderUrl
    }
    
    func convertOggToMp3(inputUrl: URL, outputUrl: URL) -> Bool  {
        let inputPath = inputUrl.path
        let outputPath = outputUrl.path
        
        let command = "-i \(inputPath) \(outputPath)"
        let session = FFmpegKit.execute(command)
        let returnCode = session?.getReturnCode()
        var result = false
        if (ReturnCode.isSuccess(returnCode)) {
            result = true
            print("Success")
        } else if ReturnCode.isCancel(returnCode) {
            print("CANCEL")
            result = false
        } else {
            print("FAILURE")
            result = false
        }
        return result
    }
    
    @objc func updateLines() {
        let randomHeight = CGFloat.random(in: 10...40)
        //        lines.append(randomHeight)
        lines.insert(randomHeight, at: 0)
        collectionView.reloadData()
        collectionView.scrollToItem(at: IndexPath(item: 0, section: 0), at: .left, animated: true)
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return lines.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
        cell.backgroundColor = .clear
        if let lineView = cell.contentView.subviews.first {
            lineView.removeFromSuperview()
        }
        let lineView = UIView(frame: CGRect(x: 0, y: 0, width: 1, height: lines[indexPath.item]))
        lineView.backgroundColor = .blue
        cell.contentView.addSubview(lineView)
        lineView.center.y = cell.center.y
        return cell
    }
    //
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 1, height: collectionView.bounds.size.height)
    }
    
    deinit {
        // 在页面销毁时停止定时器
        timer?.invalidate()
    }
}

